// pages/studyRecord/studyRecord.js
//获取应用实例
const app = getApp();
const httpUtils = require('../../utils/httpUtils.js');
const CryptoJS = require('../../utils/CryptoJS.js');
var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置


Page({

  /**
   * 页面的初始数据
   */
  data: {
    date: '', //学习日期
    type: 1, //	type 1 单词 2 阅读 3 听说 4语法 5写作
    tabs: ["单词", "阅读", "听说", "语法", "作文"],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    page: 1,
    pageSize: 20,
    hasMoreData: false,
    recordDetailList: [],
    wordNum: 0,
    innerAudioContext: new Object(),
    imageurl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
    selectedIndex: -1, //单词选中条目的下标
    selectedGrammarIndex: -1, //语法选中条目的下标
    hasreview: 0, //语法复习 0未复习，1已提交复习
    reviewLen: 0, //语法复习的长度
    audioTotalsrc: "https://vediosource.oss-cn-beijing.aliyuncs.com/grammar/US/voice/",
    showVipModal: false, //开通vip弹窗组件是否显示
    isVip: false, //vip为	0 游客 1 VIP
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //获取列表传过来的日期
    that.setData({
      date: options.date,
    })
    //初始化audio
    that.data.innerAudioContext = wx.createInnerAudioContext();
    that.data.innerAudioContext.autoplay = false;
    that.data.innerAudioContext.loop = false;

    //设置tab
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });
  },

  //点击某个Tab
  tabClick: function (e) {
    var that = this;
    that.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
    if(that.data.innerAudioContext){
      that.data.innerAudioContext.stop();
    }
 
    if (that.data.activeIndex == 0) {
      that.setData({
        type: 1,
        page: 1,
      })
    } else if (that.data.activeIndex == 1) {
      that.setData({
        type: 2,
        page: 1,
      })
    } else if (that.data.activeIndex == 2) {
      that.setData({
        type: 3,
        page: 1,
      })
    } else if (that.data.activeIndex == 3) {
      that.setData({
        type: 4,
        page: 1,
      })
    } else if (that.data.activeIndex == 4) {
      that.setData({
        type: 5,
        page: 1,
      })
    }
    //获取复习的关卡列表
    that.getStudyRecords();
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.setData({
      page: 1,
      recordDetailList: [],
      isVip: (app.globalData.studentInfo.is_vip == 1 ? true : false)
    })

    console.log("onShow-type:" + that.data.type);
    that.getStudyRecords();
  },

  /**
   * 获取该日期对应的学习记录详情
   */
  getStudyRecords: function () {
    let that = this;
    wx.showLoading({
      title: '',
      mask: true
    })

    httpUtils.getStudyRecordDetail({
      access_token: app.globalData.studentInfo.access_token ? app.globalData.studentInfo.access_token : app.globalData.access_token,
      date: that.data.date,
      type: that.data.type,
      page: that.data.page,
      size: that.data.pageSize
    }).then((res) => {
      var recordDetailList = that.data.recordDetailList;
      let list = res.data.list;

      if (that.data.page == 1) {
        recordDetailList = []
      }

      if (that.data.type == 4) {
        // that.setData({
        //   hasreview: res.data.status
        // })
        for (let i = 0; i < list.length; i++) {
          list[i].status = 0;
          list[i].click = 0;
          list[i].fontw = 'normal'
        }
      }


      if (list.length < that.data.pageSize) {
        that.setData({
          recordDetailList: recordDetailList.concat(list),
          wordNum: res.data.total,
          hasMoreData: false
        })
      } else {
        that.setData({
          recordDetailList: recordDetailList.concat(list),
          wordNum: res.data.total,
          hasMoreData: true,
          page: that.data.page + 1
        })
      }

    });

  },

  /**
   *点击单词条目，播放读音
   */
  playWordVoice: function (e) {
    this.data.innerAudioContext.stop();
    let index = e.currentTarget.dataset.index;
    let audios = e.currentTarget.dataset.audiosrc;

    // if (index == this.data.selectedIndex) {
    //   index = -1;
    // }
    this.setData({
      selectedIndex: index
    })
    this.data.innerAudioContext.src = audios;
    this.data.innerAudioContext.play();
  },

  /**
   * 点击自主复习按钮 跳转四种玩法界面
   */
  toReviewGame: function () {
    app.globalData.studyDate = this.data.date;
    wx.redirectTo({
      url: '/pages/review/review?date=' + this.data.date + '&from_channel=0',
    })
  },

  /**
   * 点击条目跳转报告界面
   */
  gotoReport: function (e) {
    let ids = e.currentTarget.dataset.id;
    var temURl = {
      '6': "/pages/notice/readreport/report",
      '1': "/pages/notice/readreport/report",
      "3": "/pages/notice/langdu/report",
      "4": "/pages/notice/tinghoujilu/report",
      "5": "/pages/notice/tinghouhuida/report",
      "2": "/pages/notice/tinghouxuanze/report",
    }

    if (temURl[this.data.recordDetailList[ids].type] != undefined) {
      wx.navigateTo({
        url: temURl[this.data.recordDetailList[ids].type] + '?id=' + this.data.recordDetailList[ids].id,
      });
    } else {
      wx.showToast({
        title: 'type=' + this.data.recordDetailList[ids].type + '没有相关报告',
        icon: 'none',
        duration: 2000
      })
    }

  },
  /**
   * 点击语法的句子列表
   */
  playGrammarVoice: function (e) {
    let that = this;
    let tmp = new Object;
    tmp = that.data.recordDetailList;
    that.data.innerAudioContext.stop();
    let idx = e.currentTarget.dataset.idx;
    console.log("idx:", idx);

    let courseid = e.currentTarget.dataset.courseid + "";
    let chapterid = e.currentTarget.dataset.chapterid + "";
    let sentenceid = e.currentTarget.dataset.id + "";
    let idstr = courseid + chapterid + sentenceid;
    console.log("idstr:" + idstr);
    let encodeStr = CryptoJS.SHA256(idstr).toString();
    that.data.innerAudioContext.src = that.data.audioTotalsrc + encodeStr + ".wav"
    console.log("videosrc:" + that.data.innerAudioContext.src)
    that.data.innerAudioContext.play();
    let hasClick = that.data.reviewLen;
    if (tmp[idx].click == 0) {
      tmp[idx].fontw = 600;
    } else if (tmp[idx].click == 1) {
      tmp[idx].bgcolor = "#D6FFE7";
      tmp[idx].status = 1;
      hasClick++;
    } else if (tmp[idx].click == 2) {
      if (tmp[idx].status == 1) {
        tmp[idx].status = 0;
      } else {
        tmp[idx].status = 1;
      }
    }
    if (tmp[idx].click < 2) {
      tmp[idx].click = parseInt(tmp[idx].click) + 1;
    }
    that.setData({
      recordDetailList: tmp,
      reviewLen: hasClick,
    })


  },

  //跳转语法复习界面
  reviewGrammar: function () {
    let that = this;
    if (that.data.isVip === false) {
      //如果不是会员，弹开通vip弹窗组件
      that.setData({
        showVipModal: true,
      })
      return false;
    } else {
      //是会员则跳转复习或查看错题
      if (that.data.hasreview == 0) {
        wx.navigateTo({
          url: '/pages/studyRecord/grammarReview/grammarReview?date=' + that.data.date,
        })
      } else if (that.data.hasreview == 1) {
        wx.navigateTo({
          url: '/pages/studyRecord/grammar/grammar?date=' + that.data.date,
        })
      }

    }
  },

  /**点击组件弹窗中的开通vip按钮 */
  goOpen: function () {
    wx.navigateTo({
      url: "/pages/vip/vipBuy",
    });
    this.setData({
      showVipModal: false,
    })
  },


  //  点击写作的条目
  toEssayDetail: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let id = e.currentTarget.dataset.id;
    let sort = e.currentTarget.dataset.sort;
    //writing_type  0范文 1词组  2万能句型
    let writing_type = e.currentTarget.dataset.type;

    if (writing_type == 0) {
      wx.navigateTo({
        url: '/pages/studyRecord/essay/essay?id=' + id + '&source=0',
      })
    } else if (writing_type == 1) {
      wx.navigateTo({
        url: '/pages/studyRecord/phrase/phrase?id=' + sort,
      })
    } else if (writing_type == 2) {
      wx.navigateTo({
        url: '/pages/studyRecord/sentencePattern/sentencePattern?id=' + sort,
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //停止播放
    let that = this;
    that.data.innerAudioContext.stop();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("onReachBottom方法触发了")
    var that = this;
    if (that.data.hasMoreData) {
      that.getStudyRecords();
      console.log("请求下一页数据")
    } else {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none'
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})